<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 style="text-align: center; margin-bottom: 30px;">登录大麦网</h2>
      


      <!-- 登录表单 -->
      <el-form 
        :model="loginForm" 
        :rules="passwordRules" 
        ref="passwordFormRef"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            size="large"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <!-- 记住用户名 -->
        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="rememberUsername">记住用户名</el-checkbox>
            <el-button type="text" @click="showForgetPassword = true">忘记密码？</el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            style="width: 100%;" 
            @click="handlePasswordLogin"
            :loading="loading"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 第三方登录 -->
      <div class="third-party-login">
        <div class="divider">
          <span>其他登录方式</span>
        </div>
        <div class="third-party-buttons">
          <el-button circle class="qq-btn" @click="thirdPartyLogin('qq')">
            <span class="icon">🐧</span>
          </el-button>
          <el-button circle class="wechat-btn" @click="thirdPartyLogin('wechat')">
            <span class="icon">💬</span>
          </el-button>
          <el-button circle class="weibo-btn" @click="thirdPartyLogin('weibo')">
            <span class="icon">🌐</span>
          </el-button>
        </div>
      </div>

      <p style="text-align: center; color: #666; margin-top: 20px;">
        还没有账号？<el-button type="text" @click="navigateToRegister">立即注册</el-button>
      </p>
    </el-card>

    <!-- 忘记密码对话框 -->
    <el-dialog v-model="showForgetPassword" title="忘记密码" width="400px">
      <el-form :model="forgetForm" :rules="forgetRules" ref="forgetFormRef">
        <el-form-item prop="username">
          <el-input 
            v-model="forgetForm.username" 
            placeholder="请输入用户名" 
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input 
            v-model="forgetForm.email" 
            placeholder="请输入注册邮箱" 
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input 
            v-model="forgetForm.newPassword" 
            type="password" 
            placeholder="请输入新密码" 
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForgetPassword = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">重置密码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../store'
import { ElMessage } from 'element-plus'
import { Iphone, Lock, Message, User } from '@element-plus/icons-vue'
import api from '../api'

export default {
  name: 'Login',
  components: {
    Iphone,
    Lock,
    Message,
    User
  },
  setup() {
    const router = useRouter()
    const store = useAppStore()
    
    const passwordFormRef = ref()
    const smsFormRef = ref()
    const forgetFormRef = ref()
    
    const showForgetPassword = ref(false)
    const loading = ref(false)
    const rememberUsername = ref(false)

    // 密码登录表单
    const loginForm = ref({
      username: '',
      password: ''
    })

    // 忘记密码表单
    const forgetForm = ref({
      username: '',
      email: '',
      newPassword: ''
    })

    // 验证规则
    const passwordRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }



    const forgetRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }

    // 加载记住的用户名
    onMounted(() => {
      const savedUsername = localStorage.getItem('savedUsername')
      if (savedUsername) {
        loginForm.value.username = savedUsername
        rememberUsername.value = true
      }
    })



    // 密码登录
    const handlePasswordLogin = () => {
      passwordFormRef.value.validate((valid) => {
        if (valid) {
          loading.value = true
          
          // 登录前先清除旧的token、用户状态和购物车数据，确保切换用户时不会混淆
          localStorage.removeItem('token')
          localStorage.removeItem('cart')
          store.setUser(null)
          store.clearCart()
          
          // 调用登录API
          api.post('/auth/login', {
            username: loginForm.value.username,
            password: loginForm.value.password
          })
            .then(response => {
              // 保存登录信息
              if (rememberUsername.value) {
                localStorage.setItem('savedUsername', loginForm.value.username)
              } else {
                localStorage.removeItem('savedUsername')
              }

              localStorage.setItem('token', response.token)
              store.setUser({
                id: response.user.id,
                username: response.user.username,
                email: response.user.email,
                is_admin: response.user.is_admin || false
              })
              
              ElMessage.success(response.message || '登录成功')
              router.push('/')
            })
            .catch(error => {
              ElMessage.error(error.response?.data?.error || '登录失败')
            })
            .finally(() => {
              loading.value = false
            })
        }
      })
    }



    // 重置密码
    const handleResetPassword = () => {
      forgetFormRef.value.validate((valid) => {
        if (valid) {
          api.post('/auth/reset-password', forgetForm.value)
            .then(() => {
              ElMessage.success('密码重置成功，请使用新密码登录')
              showForgetPassword.value = false
              forgetForm.value = {
                username: '',
                email: '',
                newPassword: ''
              }
            })
            .catch(error => {
              ElMessage.error(error.response?.data?.message || '密码重置失败')
            })
        }
      })
    }

    // 第三方登录
    const thirdPartyLogin = (type) => {
      ElMessage.info(`正在跳转${getPlatformName(type)}登录...`)
      // 这里实际应该跳转到第三方授权页面
    }

    const getPlatformName = (type) => {
      const platforms = {
        qq: 'QQ',
        wechat: '微信',
        weibo: '微博'
      }
      return platforms[type] || '第三方'
    }

    // 导航到注册页面
    const navigateToRegister = () => {
      console.log('navigateToRegister called');
      router.push({ path: '/register' });
    }

    return {
      showForgetPassword,
      loading,
      rememberUsername,
      loginForm,
      forgetForm,
      passwordRules,
      forgetRules,
      passwordFormRef,
      forgetFormRef,
      handlePasswordLogin,
      handleResetPassword,
      thirdPartyLogin,
      navigateToRegister
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 420px;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.login-tabs {
  text-align: center;
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.code-input {
  display: flex;
  gap: 10px;
}

.sms-btn {
  white-space: nowrap;
}

.third-party-login {
  margin-top: 30px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 20px 0;
  color: #999;
  font-size: 14px;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e8e8e8;
  z-index: 1;
}

.divider span {
  background: white;
  padding: 0 15px;
  position: relative;
  z-index: 2;
}

.third-party-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.third-party-buttons .el-button {
  width: 50px;
  height: 50px;
  font-size: 20px;
}

.qq-btn {
  background: #12b7f5;
  border-color: #12b7f5;
  color: white;
}

.wechat-btn {
  background: #07c160;
  border-color: #07c160;
  color: white;
}

.weibo-btn {
  background: #e6162d;
  border-color: #e6162d;
  color: white;
}

.third-party-buttons .el-button:hover {
  opacity: 0.8;
  transform: scale(1.05);
}

.icon {
  font-size: 24px;
}
</style>